package com.item.action;

import java.io.InputStream;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.base.action.CoreController;
import com.base.dao.model.BFile;
import com.base.dao.model.Ret;
import com.base.dialect.PaginationSupport;
import com.base.service.BFileService;
import com.base.support.PropertySupport;
import com.base.util.ExcelReader;
import com.base.util.JSONUtils;
import com.base.util.ToolsUtil;
import com.base.web.annotation.LoginFilter;
import com.item.dao.model.Message;
import com.item.dao.model.MessageExample;
import com.item.dao.model.UserExample;
import com.item.service.MessageService;
import com.item.service.UserService;

@RequestMapping("msg")
@Controller
@LoginFilter
public class MessageController extends CoreController{

    @Autowired
    private MessageService messageService;
    @Autowired
    private UserService userService;
    @Autowired
    private BFileService fileService;
    
    @RequestMapping("/list")
	@ResponseBody 
    public String list(Integer page, Integer rows){
    	PaginationSupport.byPage(page, rows);
    	MessageExample example = new MessageExample();
    	example.setOrderByClause("create_time desc");
    	List<Message> list = messageService.selectByExample(example);
      	return page(list);
    }
    
    @RequestMapping("/save")
	@ResponseBody 
    public String save(Message message){
    	Ret ret = new Ret(0);
    	if (message.getType() == 2) {
			List<Integer> idList = userService.selectIdByAccounts(Arrays.asList(message.getAccounts().split(",")));
			if (idList == null || idList.size() == 0) {
				ret.setCode(1);
				ret.setMsg("用户账号不存在");
				return ok(ret);
			}
    		message.setTarget(ToolsUtil.getStrWithChar(idList, null));
		}
    	
    	if (message.getId() == null){
    		message.setRedirectType(1);
    		message.setNum(0);
    		message.setCreateTime(new Date());
    		message.setState(1);
    		messageService.insert(message);
    	}else{
    		Message temp = messageService.selectByPrimaryKey(message.getId());
			if(temp == null || temp.getState() == 2){
				return msg(1,"已推送的记录无法修改");
			}
			message.setRedirectType(1);
			message.setNum(0);
			message.setState(1);
			message.setCreateTime(temp.getCreateTime());
    		messageService.updateByPrimaryKeyWithBLOBs(message);
    	}
       	return ok(ret);
    }
    
    @RequestMapping("/findById")
	@ResponseBody 
    public String find(Integer id){
    	Message message = messageService.selectByPrimaryKey(id);
//    	String account = userService.selectAccountById(message.getTarget());
//    	message.setTarget(account);
       	return ok(message);
    }
    
    @RequestMapping("/del")
	@ResponseBody 
    public String del(String id){
    	String[] ids = id.split(",");
    	for (String str : ids){
    		messageService.deleteByPrimaryKey(Integer.parseInt(str));
    	}
       	return ok();
    }

	
	@RequestMapping("/send")
	@ResponseBody
	public String send(Integer id){
		if(StringUtils.isBlank(PropertySupport.getProperty("jpush.appkey"))){
			return msg(1,"系统尚未开启推送服务！");
		}
		
		Message message = messageService.selectByPrimaryKey(id);
		
		if(message==null){
			return msg(1,"消息不存在");
		}
		
		if(message.getState() == 2){
			return msg(1,"消息已被推送过了~");
		}
		//如果是个推的情况下，判断这个用户是否存在
		if(message.getType() == 2){
			/*UserExample example = new UserExample();
			example.createCriteria().andIdEqualTo(Integer.parseInt(message.getTarget()));
			List<User> list = userService.selectByExample(example);*/
			if (StringUtils.isBlank(message.getTarget())) {
				return msg(1,"该用户不存在");
			}
//			if(list.size() > 1){
//				return msg(1,"用户信息有误,请联系开发人员");
//			}
		}
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("redirectType", 1);
		params.put("msg", message.getContent());
		String ret = "";
		if(message.getType() == 1){
			ret = messageService.pushToApp(message.getContent(),1,"");
		}else if(message.getType() == 2){
			String[] idArray = message.getTarget().split(",");
			List<Integer> idList = new LinkedList<Integer>();
			for (String ele : idArray) {
				idList.add(Integer.parseInt(ele));
			}
			ret = messageService.pushToList(idList, message.getContent(), 1, "");
//			ret = messageService.pushToSingle(Integer.parseInt(message.getTarget()), message.getContent(), 1, "");
		}
		
		if(StringUtils.isBlank(ret)){
			return msg(1,"推送失败，请联系开发人员，确认是否推送已接入");
		}
		
		if(ret.contains("sendno")){
			message.setState(2);
			messageService.updateByPrimaryKey(message);
		}else{
			return msg(1,"推送失败,返回值："+ret);
		}
		
		return ok();
	}
	
	@RequestMapping("/userIsNoExist")
	@ResponseBody
	public String userIsNoExist(String value){
		UserExample example = new UserExample();
		example.createCriteria().andAccountEqualTo(value);
		int cnt = userService.countByExample(example);
		if(cnt>0){
	           return JSONUtils.serialize(new Ret(0)); 
	       }        
	       return JSONUtils.serialize(new Ret(1));
	}
	
	@RequestMapping("/importData")
	@ResponseBody
	public String importData(String fileId) {
		Ret ret = new Ret(0);
		BFile item = fileService.selectByPrimaryKey(fileId);
		if (item == null) {
			ret.setCode(1);
			ret.setMsg("文件不存在");
			return ok(ret);
		}
		InputStream is = null;
		try {
			is = ToolsUtil.getFileStream(item.getFileBelong(), item.getFilePath());
		} catch (Exception e) {
			logger.error(new StringBuilder().append("文件没找到;id=").append(fileId).toString());
			ret.setCode(1);
			ret.setMsg("文件不存在");
			return ok(ret);
		}
		
		ExcelReader reader = new ExcelReader(is);
		int rows = reader.getRowNum(0);
		int columns = reader.getColumnNum(0);
		if (columns != 1) {
			ret.setCode(2);
			ret.setMsg("excel表头应该包含1项");
			return ok(ret);
		}
		if (rows < 1) {
			ret.setCode(2);
			ret.setMsg("excel表未写入数据");
			return ok(ret);
		}
		Set<String> sets = new TreeSet<String>();
		for (int i = 1; i <= rows; i++) {
			try {
				sets.add(reader.read(0, 0, i));
			} catch (Exception ex) {
				ret.setCode(3);
				ret.setMsg(ToolsUtil.getPlaceholderStr("第{0}行数据有问题", i));
				break;
			}
		}
		StringBuffer buf = new StringBuffer();
		for (Iterator<String> iter = sets.iterator(); iter.hasNext(); ) {
			buf.append(iter.next()).append(",");
		}
		ret.setMsg(buf.substring(0, buf.length() - 1));
		return ok(ret);
	}
	
}
